import pandas as pd
import datetime

def str2datetime(strdate,segment="-"):
    if isinstance(strdate,str):
        if len(strdate)==8:
            fromt=datetime.datetime.strptime(strdate,"%Y%m%d")
        elif len(strdate)==10:
            s="%Y"+segment+"%m"+segment+"%d"
            fromt=datetime.datetime.strptime(strdate,s)
        elif len(strdate)==14:
            fromt = datetime.datetime.strptime(strdate, "%Y%m%d%H%M%S")
        elif len(strdate)==12:
            fromt = datetime.datetime.strptime(strdate, "%Y%m%d%H%M")
        elif len(strdate)==17:
            fromt=datetime.datetime.strptime(strdate,"%Y%m%d %H:%M:%S")
        else:
            s="%Y"+segment+"%m"+segment+"%d %H:%M:%S"
            fromt=datetime.datetime.strptime(strdate,s)
    else:
        fromt=strdate
    return fromt
def datetime2datestr(date,strframt="%Y%m%d"):
    rst=date
    if isinstance(date,datetime.datetime):
        rst= date.strftime(strframt)
    return rst
def converttype(t,datatype):
    rst=t 
    if isinstance(t,dict):
        if rst:
            if datatype in ["DF","DataFrame","df","pd.DataFrame"]:
                for i in t.values():
                    if isinstance(i,dict): 
                        rst=pd.DataFrame(t).T
                    else:
                        rst=pd.DataFrame(t)
                    break
            elif datatype=="list":
                rst=list(t.values())
    elif isinstance(t,pd.DataFrame):
        if datatype =="dict":
            rst=t.to_dict("index")
        elif datatype=="list":
            rst=t.to_dict("records")
    elif isinstance(t,list):
        if rst:
            if datatype in ["DF","DataFrame","df","pd.DataFrame"]:
                rst=pd.DataFrame(t)
                if "timekey" in rst.columns.tolist():
                    rst.index=pd.to_datetime(rst["timekey"])
            elif datatype=="dict":
                if isinstance(t[0],dict):
                    if "timekey" in t[0].keys():
                        for i in t:
                            key=i["timekey"]
                            rst[key]=i
                    else:
                        keyname =t[0].keys()[0]
                        for i in t:
                            key=i[keyname]
                            rst[key]=i
                else:
                    key=0
                    for i in t:
                        rst[key]=i 
                        key=key+1
    return rst
alias_name={}
def addaliasname(alias):
    for k,v in alias.items():
        for i in v:
            if i not in alias_name.keys():
                alias_name[i]=k
alias_tick=dict(
    data=["d"]
)
addaliasname(alias_tick)
def originalname(argkv):
    for k,v in argkv.items():
        if k in alias_name.keys():
            name=alias_name[k]
            argkv[name]=v
def arg2argkv(arg,argkv,argkey):
    if arg:
        n=len(arg)
        for i in range(n):
            key=argkey[i]
            argkv[key]=arg[i]